<?php

namespace Forms;

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\TextArea;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Check;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\Identical;
use Phalcon\Validation\Message;
use Phalcon\Validation\Message\Group;
use Phalcon\Mvc\Model\Message as ModelMessage;

class ContactForm extends Form {

    public function initialize($entity = null, $options = null) {
        $name = new Text('name');
        $name->setLabel('Họ tên');
        $name->addValidators(array(
            new PresenceOf(array(
                'message' => 'Vui lòng nhập họ tên'
                    ))
        ));

        $this->add($name);

        // Email
        $email = new Text('email');

        $email->setLabel('E-Mail');

        $email->addValidators(array(
            new PresenceOf(array(
                'message' => 'Vui lòng nhập địa chỉ email'
                    )),
            new Email(array(
                'message' => 'Email không đúng'
                    ))
        ));

        $this->add($email);

        // Content
        $content = new TextArea('content');

        $content->setLabel('Tin nhắn');

        $content->addValidators(array(
            new PresenceOf(array(
                'message' => 'Vui lòng nhập nội dung liên hệ'
                    )),
        ));

        $this->add($content);

        // Remember
        $sendmail = new Check('sendmail', array(
            'value' => 'yes'
        ));

        $sendmail->setLabel('Gửi một bản sao của email này cho chính mình');

        $this->add($sendmail);

        // CSRF
        $csrf = new Hidden('csrf');

        $csrf->addValidator(new Identical(array(
            'value' => $this->security->getSessionToken(),
            'message' => 'CSRF validation failed'
        )));

        $this->add($csrf);
    }

    /**
     * Prints messages for a specific element
     */
    public function messages($name) {
        if ($this->hasMessagesFor($name)) {
            foreach ($this->getMessagesFor($name) as $message) {
                $this->flash->error($message);
            }
        }
    }

    public function appendMessage($message, $field, $type = null) {
        if (is_string($message)) {
            $message = new Message($message, $field, $type);
        }

        if ($message instanceof Message || $message instanceof ModelMessage) {
            // Check if there is a group for the field already.
            if (!is_null($this->_messages) && array_key_exists($field, $this->_messages)) {
                $this->_messages[$field]->appendMessage($message);
            } else {
                $this->_messages[$field] = new \Phalcon\Validation\Message\Group(array($message));
            }
        } else {
            throw new Exception("Can't append message into the form, invalid type.");
        }
    }

}
